package com.xxl.job.executor.core.config;

import com.alibaba.fastjson.JSON;
import com.xxl.job.core.biz.model.DbInfo;
import com.xxl.job.core.enums.DbinfoBelongEnum;
import com.xxl.job.core.util.ListUtils;
import com.xxl.job.executor.dao.DbInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


//@Configuration
public class DataSourceConfig {

    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.driverClassName}")
    private String driverClassName;

    @Autowired(required = false)
    private DbInfoMapper dbInfoMapper;

    @Bean(name="sharedJdbcTemplate")
    public JdbcTemplate getJdbcTemplate(){
        Map<String, String> map = new HashMap<>();
        map.put("dbType", "1");//MYSQL
        map.put("belong", DbinfoBelongEnum.SHARED.getKey());
        List<DbInfo> dbInfos = dbInfoMapper.query(map);
        System.out.println(JSON.toJSONString(dbInfos));
        if(ListUtils.isNotEmpty(dbInfos)) {
            DbInfo dbInfo = dbInfos.get(0);
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(dbInfo.getDbDriver());
            dataSource.setUrl(dbInfo.getDbUrl());
            dataSource.setUsername(dbInfo.getDbUserName());
            dataSource.setPassword(dbInfo.getDbPassword());
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            return jdbcTemplate;
        } else {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            return jdbcTemplate;
        }
    }
}
